package com.itheima.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.itheima.bean.News;
import com.itheima.service.NewsService;
import com.itheima.service.impl.NewsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/newsServlet")
public class NewsServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 解决请求和响应中文乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        //2 获取请求参数：currentPage和pageSize
        String currentPage = req.getParameter("currentPage");
        String pageSize = req.getParameter("pageSize");

        //3 调用service，查询分页结果：pageInfo
        NewsService newsService=new NewsServiceImpl();
        PageInfo<News> pageInfo = newsService.pageQuery(Integer.parseInt(currentPage), Integer.parseInt(pageSize));

        //4 将pageInfo转换成json发送给客户端
        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.writeValue(resp.getWriter(),pageInfo);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
